const { updateApiClient } = require("./api.js")
const defaultConfig = {
  opacity: 0.8,
  mainColor: '#49CE95',
  subColor: '#FA0A55',
  nsLow: 4.5,
  nsHigh: 8.5,
  isOn: false
}

let cacheConfig = null;

const getConfig = () => {
  if (cacheConfig) {
    return cacheConfig
  }
  const config = localStorage.getItem('config')
  let resultConfig = config?JSON.parse(config):defaultConfig
  cacheConfig = resultConfig;
  return resultConfig
}

const setConfig = (data) => {
  cacheConfig = data;
  localStorage.setItem('config', JSON.stringify(data))
}

const setInMemConfig = (data) => {
  cacheConfig = data;
}

const getValue = (key) => {
  const config = getConfig()
  return config[key]
}

/**
 * 在页面内调用该方法设置css变量
 */
const applyConfig = () => {
  const config = getConfig()
  document.documentElement.style.setProperty('--main-color', config.mainColor)
  document.documentElement.style.setProperty('--sub-color', config.subColor)
  document.documentElement.style.setProperty('--opacity', config.opacity)

  //  对api进行初始化
  updateApiClient(getValue("nsAddr"),getValue("nsSecret"))
}



module.exports = {
  defaultConfig,
  getConfig,
  applyConfig,
  getValue,
  setConfig,
  setInMemConfig
}
